﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
#region 引用SS
using SuperSocket.ClientEngine;
using SuperSocket.ProtoBase;
using Mode;
using Newtonsoft.Json;
#endregion
namespace SS.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            EasyClient<BinaryPackageInfo<Int16>> SSClient = new EasyClient<BinaryPackageInfo<short>>();
            SSClient.Initialize(new FixedHeaderReceiveFilter());
            SSClient.Connected += (sender, e) =>
            {
                string tmpStr = "Data Source=" + "SINOMAC" + "\\SQLEXPRESS;Initial Catalog=PrintPMIS;User Id=sa;Password=ssa;";
                Console.WriteLine("client is connected");

                #region 测试读取数据库的DataSet

                DataSet ds = new DataSet();
                try
                {
                    //读取数据库
                    SqlConnection con = new SqlConnection(tmpStr);
                    SqlDataAdapter dap = new SqlDataAdapter("PRO_Porject_AllView", con);
                    dap.SelectCommand.CommandType = CommandType.StoredProcedure;

                    dap.Fill(ds);
                    con.Close();
                }
                catch// (Exception E)
                {

                }

                #endregion

                byte[] info = SerializationHelpers.ObjectToByte(ds);
                var o = new ArraySegment<byte>(BitConverter.GetBytes(info.Length).Concat(info).ToArray());
                (sender as EasyClientBase).Send(o);
                /*            
                Interlocked.Increment(ref ConnectedCount);
                Message message = new Message() { Name = "test", Msg = "dsjidjisjdi" };
                byte[] bytes =BitConverter.GetBytes((short)1).Concat(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))).ToArray();
                var o = new ArraySegment<byte>(BitConverter.GetBytes(bytes.Length).Concat(bytes).ToArray());

                (sender as EasyClientBase).Send(o);
              */
            };
            SSClient.NewPackageReceived += (sender, e) =>
            {
                Byte[] bytes = BitConverter.GetBytes(Convert.ToInt16(e.Package.Key)).Concat(e.Package.Data).ToArray();
                var obj = new ArraySegment<byte>(BitConverter.GetBytes(bytes.Length).Concat(bytes).ToArray());
                (sender as EasyClientBase).Send(obj);


                Console.WriteLine("Data");
            };

            SSClient.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 5000));


            Console.WriteLine("Entery Any Key Quit The Client");
            Console.ReadKey();
        }
    }
}
